# Maintainer: Martell Malone <martell malone at g mail dot com >

_realname=libwebsockets
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.2.2
pkgrel=2
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
pkgdesc="C library for websocket clients and servers (mingw-w64)"
url='https://libwebsockets.org/'
license=('LGPL2.1')
depends=("${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/warmcat/${_realname}/archive/v${pkgver}.tar.gz"
        001-posix-layout.patch
        002-cmake-remove-build-hash.patch
        003-install-pkgconfig-files.patch)
options=(!strip !buildflags staticlibs)
sha256sums=('c2ae635485b8ef8d383dee0aee29ad6272d4462e527d29d9af014ab4a2465cbd'
            '9bdfdffc74e348692b20b08881ec682ee7aa7ba65b370199dd52f99331013cdc'
            '90ad5e561980d820ffe2c84823e4da16bfb875d205cfedab221543436ab702b7'
            '20fe459b7b666c4744431d9e40c9fe453b97973655ea9ad982ff0d54afb3a706')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/001-posix-layout.patch
  patch -p1 -i ${srcdir}/002-cmake-remove-build-hash.patch

  # https://github.com/warmcat/libwebsockets/pull/2409
  patch -p1 -i ${srcdir}/003-install-pkgconfig-files.patch
}

build() {
  [[ -d ${srcdir}/build-${MINGW_CHOST} ]] && rm -rf ${srcdir}/build-${MINGW_CHOST}
  mkdir -p ${srcdir}/build-${MINGW_CHOST} && cd ${srcdir}/build-${MINGW_CHOST}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DLWS_WITH_DIR=OFF \
    -DLWS_WITHOUT_DAEMONIZE=ON \
    -DLWS_WITHOUT_TESTAPPS=ON \
    -DCMAKE_BUILD_TYPE=Release \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd ${srcdir}/build-${MINGW_CHOST}
  DESTDIR=${pkgdir} ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install
  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/${_realname}/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
    sed -e "s|${MINGW_PREFIX}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
